package org.jeecg.modules.ocr.utils;

import cn.hutool.core.util.ReUtil;
import com.benjaminwan.ocrlibrary.OcrResult;
import io.github.mymonstercat.Model;
import io.github.mymonstercat.ocr.InferenceEngine;
import io.github.mymonstercat.ocr.config.ParamConfig;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * <p>
 *  OCR识别工具类
 * </p>
 *
 * @author 29shusheng
 * @date 2024-7-25 17:58:36
 */


public class OCRUtil {

    /**
     * OCR识别
     * @param fileUpload 图片
     * @return
     * @throws IOException
     */
    public static String ocrResult(MultipartFile fileUpload) throws IOException {
        ParamConfig paramConfig = ParamConfig.getDefaultConfig();
        paramConfig.setDoAngle(true);
        paramConfig.setMostAngle(true);
        InferenceEngine engine = InferenceEngine.getInstance(Model.ONNX_PPOCR_V3);
        File file = new File("D:\\scholar-ai\\file");
        if (!file.exists()) {
            // 创建文件根目录
            file.mkdirs();
        }
        fileUpload.transferTo(file);
        file.deleteOnExit();
        OcrResult ocrResult = engine.runOcr(file.getPath(),paramConfig);
        return ocrResult.getStrRes();
    }

    /**
     * 身份证识别
     * @param ocrResult
     * @return
     */
    public static boolean ocrIdcard(String ocrResult) {
        // 身份证校验
        String idCardRegex = "\\d{17}[\\dXx]";
        String cardNumber = ReUtil.getGroup0(idCardRegex, ocrResult);
        System.out.println("识别的身份证号："+cardNumber);
        if (cardNumber != null) {
            // 识别出的身份证校验
            String idCardRegex1 = "^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\\d{3}(\\d|X|x)$";
            String cardNumber1 = ReUtil.getGroup0(idCardRegex1, cardNumber);
            if (cardNumber1 != null) {
                System.out.println("身份证校验通过");
                return true;
            } else {
                System.out.println("身份证校验不通过");
                return false;
            }
        } else {
            System.out.println("身份证校验不通过");
            return false;
        }
    }
    /**
     * 不动产单元号识别
     * @param ocrResult
     * @return
     */
    public static boolean ocrBdc(String ocrResult) {
        // 不动产单元号校验（28位，前12位和后四位位数字，中间12位任意字符）
        String idCardRegex = "\\d{12}.{12}\\d{4}";
        String number = ReUtil.getGroup0(idCardRegex, ocrResult);
        return number != null;
    }


}
